﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace XNA_TD
{
    class DebugInfo : IRunable, IUpdate, IDraw
    {
        private static DebugInfo instance;
        private Dictionary<string, KeyValuePair<double,Object>> infos;
        public SpriteFont debugFont;

        private DebugInfo()
            : base(Priority.GUI)
        {
            infos = new Dictionary<string, KeyValuePair<double, Object>>();
            debugFont = Content.Load<SpriteFont>("debugfont");
            Register(this);
        }

        public void add(string key, Object Object)
        {
            if (infos.ContainsKey(key))
            {
                infos[key] = new KeyValuePair<double,object>(gameTime.TotalGameTime.TotalSeconds, Object);
            }
            else
            {
                infos.Add(key, new KeyValuePair<double, object>(gameTime.TotalGameTime.TotalSeconds, Object));
            }
        }

        public void remove(string key)
        {
            infos.Remove(key);
        }

        public void Draw()
        {
            var depthStencilState = graphics.GraphicsDevice.DepthStencilState;
            spriteBatch.Begin();
            Vector2 pos = new Vector2(0, 0);
            foreach (KeyValuePair<string, KeyValuePair<double,Object>> pair in infos)
            {
                spriteBatch.DrawString(debugFont, pair.Key + ": " + pair.Value.Value.ToString(), pos, Color.Black);
                pos.Y += 12;
            }
            spriteBatch.End();
            graphics.GraphicsDevice.DepthStencilState = depthStencilState;
        }

        public static DebugInfo Instance
        {
            get 
            {
                if (instance == null)
                {
                    instance = new DebugInfo();
                }
                return instance;
            }
        }

        public void Update()
        {
            List<string> toDelete = new List<string>();
            foreach (var info in infos)
            {
                if (info.Value.Key + 2 < gameTime.TotalGameTime.TotalSeconds)
                {
                    toDelete.Add(info.Key);
                }
            }
            foreach (var key in toDelete)
            {
                infos.Remove(key);
            }
        }

        public override void Load()
        {
        }

        public override void UnLoad()
        {
        }
    }
}
